package com.zzw.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 使用ThreadPoolExecutor的服务类
 */
@Service
public class ThreadPoolTaskService {
    
    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolTaskService.class);
    
    @Autowired
    @Qualifier("threadPoolExecutor")
    private ThreadPoolExecutor threadPoolExecutor;
    
    /**
     * 提交Runnable任务到线程池
     * @param taskName 任务名称
     */
    public void submitTask(String taskName) {
        threadPoolExecutor.execute(() -> {
            logger.info("开始执行Runnable任务: {}", taskName);
            try {
                // 模拟耗时操作
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                logger.error("任务执行被中断: {}", e.getMessage());
            }
            logger.info("Runnable任务执行完成: {}, 线程名: {}", 
                    taskName, Thread.currentThread().getName());
        });
    }
    
    /**
     * 提交Callable任务到线程池，带返回值
     * @param taskName 任务名称
     * @return 任务执行结果Future
     */
    public Future<String> submitTaskWithResult(String taskName) {
        return threadPoolExecutor.submit(() -> {
            logger.info("开始执行Callable任务: {}", taskName);
            try {
                // 模拟耗时操作
                Thread.sleep(2500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw e;
            }
            logger.info("Callable任务执行完成: {}, 线程名: {}", 
                    taskName, Thread.currentThread().getName());
            return "Callable任务[" + taskName + "]执行成功";
        });
    }
    
    /**
     * 批量提交任务
     * @param taskCount 任务数量
     * @return 任务执行结果列表
     */
    public List<Future<String>> submitBatchTasks(int taskCount) {
        List<Future<String>> results = new ArrayList<>();
        
        for (int i = 1; i <= taskCount; i++) {
            final int taskId = i;
            Callable<String> task = () -> {
                String taskName = "批量任务-" + taskId;
                logger.info("开始执行批量任务: {}", taskName);
                try {
                    // 模拟耗时操作，随机休眠1-3秒
                    Thread.sleep((long) (1000 + Math.random() * 2000));
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw e;
                }
                logger.info("批量任务执行完成: {}, 线程名: {}", 
                        taskName, Thread.currentThread().getName());
                return "批量任务[" + taskName + "]执行成功";
            };
            
            results.add(threadPoolExecutor.submit(task));
        }
        
        return results;
    }
    
    /**
     * 获取线程池信息
     * @return 线程池状态信息
     */
    public String getThreadPoolInfo() {
        return String.format("线程池状态 - 核心线程数: %d, 当前线程数: %d, 活动线程数: %d, 已完成任务数: %d, 队列任务数: %d",
                threadPoolExecutor.getCorePoolSize(),
                threadPoolExecutor.getPoolSize(),
                threadPoolExecutor.getActiveCount(),
                threadPoolExecutor.getCompletedTaskCount(),
                threadPoolExecutor.getQueue().size());
    }
} 